package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDynamicMaintenanceDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author: xy
 * @Date: create in 2020/3/8
 * @description:
 * @version: 1.0
 */
@Slf4j
@Service
public class UserDynamicMaintenanceServiceImpl implements UserDynamicMaintenanceService {

    @Autowired
    UserDynamicMaintenanceDao userDynamicMaintenanceDao;
    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        log.debug("service:" + queryPageBean);
        //1. 开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //2. 条件查询
        Page<SysUser> page = userDynamicMaintenanceDao.findByCondition(queryPageBean.getQueryString());
        log.debug("page{"+page+"}");
        //封装PageResult
        return new PageResult(page.getTotal(), page);
    }

    @Override
    public void add(SysUser sysUser, Integer[] roleIds) {
        userDynamicMaintenanceDao.add(sysUser);
        if (sysUser.getId()!= null && roleIds != null && roleIds.length> 0){
            for (Integer roleId : roleIds) {
                userDynamicMaintenanceDao.set(sysUser.getId(),roleId);
            }
        }

    }

    @Override
    public void delById(Integer id) {
        userDynamicMaintenanceDao.delById(id);
        userDynamicMaintenanceDao.delRelation(id);
    }

    @Override
    public SysUser findById(Integer id) {
        return userDynamicMaintenanceDao.findById(id);
    }

    @Override
    public void edit(SysUser sysUser,Integer[] roleIds) {
//        修改用户
        userDynamicMaintenanceDao.edit(sysUser);
//         先删除关系
        userDynamicMaintenanceDao.delRelation(sysUser.getId());
        if(sysUser.getId() != null && roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                userDynamicMaintenanceDao.set(sysUser.getId(),roleId);
            }
        }

    }

    @Override
    public List<Integer> findRoleIdsById(Integer id) {
        return userDynamicMaintenanceDao.findRoleIdsById(id);
    }
}
